const jwt = require('jsonwebtoken');
const { db } = require('../config/database');

// JWT验证中间件
const authenticateToken = async (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ message: '访问令牌缺失' });
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    
    // 从数据库获取用户信息
    const user = await db.oneOrNone(
      'SELECT id, username, email, role FROM users WHERE id = $1',
      [decoded.userId]
    );

    if (!user) {
      return res.status(401).json({ message: '用户不存在' });
    }

    req.user = user;
    next();
  } catch (error) {
    if (error.name === 'TokenExpiredError') {
      return res.status(401).json({ message: '访问令牌已过期' });
    } else if (error.name === 'JsonWebTokenError') {
      return res.status(401).json({ message: '无效的访问令牌' });
    } else {
      return res.status(500).json({ message: '服务器错误' });
    }
  }
};

// 角色权限验证中间件
const requireRole = (roles) => {
  return (req, res, next) => {
    if (!req.user) {
      return res.status(401).json({ message: '未认证' });
    }

    if (!roles.includes(req.user.role)) {
      return res.status(403).json({ message: '权限不足' });
    }

    next();
  };
};

// KP权限验证中间件
const requireKP = async (req, res, next) => {
  try {
    const roomId = req.params.roomId || req.body.roomId;
    
    if (!roomId) {
      return res.status(400).json({ message: '房间ID缺失' });
    }

    const room = await db.oneOrNone(
      'SELECT kp_id FROM rooms WHERE id = $1',
      [roomId]
    );

    if (!room) {
      return res.status(404).json({ message: '房间不存在' });
    }

    if (room.kp_id !== req.user.id) {
      return res.status(403).json({ message: '只有KP可以执行此操作' });
    }

    next();
  } catch (error) {
    return res.status(500).json({ message: '服务器错误' });
  }
};

module.exports = {
  authenticateToken,
  requireRole,
  requireKP
};
